package com.example.frp_http_proxy

import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** FrpHttpProxyPlugin */
class FrpHttpProxyPlugin: FlutterPlugin, MethodCallHandler {

    companion object {
        private const val TAG = "FrpHttpProxyPlugin"
        private const val CHANNEL_NAME = "frp_http_proxy"

        // 方法名常量
        private const val METHOD_GET_PLATFORM_VERSION = "getPlatformVersion"
        private const val METHOD_RUN = "run"
        private const val METHOD_DOWN_APP = "downApp"
        private const val METHOD_GET_SERVICE_STATUS = "getServiceStatus"

        // 参数名常量
        private const val ARG_PORT = "port"
        private const val ARG_NAME = "name"
        private const val ARG_IP = "ip"
        private const val ARG_PID = "pid"
    }

    private lateinit var applicationContext: Context
    private lateinit var methodChannel: MethodChannel

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        applicationContext = flutterPluginBinding.applicationContext
        methodChannel = MethodChannel(flutterPluginBinding.binaryMessenger, CHANNEL_NAME)
        methodChannel.setMethodCallHandler(this)
        Log.d(TAG, "Plugin attached to engine")
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        Log.d(TAG, "Method called: ${call.method}")

        try {
            when (call.method) {
                METHOD_GET_PLATFORM_VERSION -> {
                    result.success("Android ${android.os.Build.VERSION.RELEASE}")
                }

                METHOD_RUN -> {
                    handleRunMethod(call, result)
                }

                METHOD_DOWN_APP -> {
                    handleDownAppMethod(call, result)
                }

                METHOD_GET_SERVICE_STATUS -> {
                    result.success(mapOf(
                        "isRunning" to FrpService.isServiceRunning(),
                        "status" to if (FrpService.isServiceRunning()) "running" else "stopped"
                    ))
                }

                else -> {
                    Log.w(TAG, "Unknown method: ${call.method}")
                    result.notImplemented()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error handling method call: ${call.method}", e)
            result.error("PLUGIN_ERROR", "Error: ${e.message}", e.toString())
        }
    }

    private fun handleRunMethod(call: MethodCall, result: Result) {
        val port: String? = call.argument(ARG_PORT)
        val name: String? = call.argument(ARG_NAME)
        val ip: String? = call.argument(ARG_IP)

        // 参数验证
        if (port.isNullOrBlank() || name.isNullOrBlank() || ip.isNullOrBlank()) {
            result.error("INVALID_ARGUMENTS", "Port, name, and ip are required", null)
            return
        }

        // 检查服务是否已经在运行
        if (FrpService.isServiceRunning()) {
            Log.w(TAG, "Service is already running")
            result.success("Service is already running")
            return
        }

        try {
            val serviceIntent = Intent(applicationContext, FrpService::class.java).apply {
                putExtra(FrpService.EXTRA_PORT, port)
                putExtra(FrpService.EXTRA_NAME, name)
                putExtra(FrpService.EXTRA_IP, ip)
            }

            applicationContext.startService(serviceIntent)
            Log.i(TAG, "FRP service started with parameters: port=$port, name=$name, ip=$ip")
            result.success("Service started successfully")

        } catch (e: Exception) {
            Log.e(TAG, "Failed to start service", e)
            result.error("SERVICE_START_ERROR", "Failed to start service: ${e.message}", null)
        }
    }

    private fun handleDownAppMethod(call: MethodCall, result: Result) {
        val pid: String? = call.argument(ARG_PID)

        try {
            if (FrpService.isServiceRunning()) {
                val stopIntent = Intent(applicationContext, FrpService::class.java).apply {
                    action = FrpService.ACTION_STOP
                }
                applicationContext.startService(stopIntent)
                Log.i(TAG, "Stop service command sent")
                result.success("Service stop command sent")
            } else {
                Log.w(TAG, "Service is not running")
                result.success("Service is not running")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Failed to stop service", e)
            result.error("SERVICE_STOP_ERROR", "Failed to stop service: ${e.message}", null)
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel.setMethodCallHandler(null)
        Log.d(TAG, "Plugin detached from engine")
    }
}
